<template>
  <div class="c-bg-white c-flex-column">
    <section class="c-ph24 c-pv30 c-flex-row">
      <div class="c-ww180 c-hh120 c-p" @click="tapGoDetail">
        <CoverImg prodType="7" coverSizeClass="c-w100 c-h c-text-hidden c-br16" imgClass="c-br16" :coverUrl="$addXossFilter(shopInfo.cover)" />
        <div class="c-br8 c-hh28 c-lh30 c-ph6 c-textAlign-c c-translucent-balck60 c-fs18 c-fc-white c-pa c-p-b8 c-p-r8 c-pz9">活动</div>
      </div>
      <div class="c-pl20 c-flex-grow1 c-w0 c-flex-column c-justify-sb">
        <div class="c-fs24 c-fw-b c-text-ellipsis2">{{ shopInfo.name }}</div>
        <div v-if="shopInfo.priceInfo" class="c-fc-xmlred c-flex-row c-aligni-center c-lh26 c-hh26 c-fw-b">
          <span v-if="shopInfo.priceInfo.beforeSymbol" class="c-fs20">{{shopInfo.priceInfo.beforeSymbol}}</span>
          <span class="c-lh26 c-hh26" :class="shopInfo.priceInfo.isText == 1 ? 'c-fs24':'c-fs26'">{{shopInfo.priceInfo.price}}</span>
          <span v-if="shopInfo.priceInfo.afterSymbol" class="c-fs18">{{shopInfo.priceInfo.afterSymbol}}</span>
        </div>
      </div>
    </section>
    <section class="c-bd-t12-f5 c-pv30">
      <div class="c-fs30 c-fw-b c-ph24">我的推广数据</div>
      <div class="c-flex-row c-pt30">
        <div class="c-flex-column c-flex-center c-flex-grow1">
          <span class="c-fs32 c-fw-b c-lh44">{{traceData.visitCount}}</span>
          <span class="c-fs22 c-fc-gray c-lh32 c-mt4">浏览数量</span>
        </div>
        <div class="c-flex-column c-flex-center c-flex-grow1">
          <span class="c-fs32 c-fw-b c-lh44">{{traceData.orderCount}}</span>
          <span class="c-fs22 c-fc-gray c-lh32 c-mt4">订单数量</span>
        </div>
        <div class="c-flex-column c-flex-center c-flex-grow1">
          <span class="c-fs32 c-fw-b c-lh44">{{traceData.avgPrice}}</span>
          <span class="c-fs22 c-fc-gray c-lh32 c-mt4">客单价(元)</span>
        </div>
        <div class="c-flex-column c-flex-center c-flex-grow1">
          <span class="c-fs32 c-fw-b c-lh44">{{traceData.paidMoney}}</span>
          <span class="c-fs22 c-fc-gray c-lh32 c-mt4">成交金额(元)</span>
        </div>
      </div>
    </section>
    <section class="c-bd-t12-f5 c-pt30 c-ph24">
      <div class="c-fs30 c-fw-b c-pb20">销售线索</div>
      <div v-if="curDate" class="c-flex-row c-aligni-center c-pv20 c-bg-white c-p-sticky c-pz10" :class="showNavBar ? 'c-p-t64':'c-p-t0'">
        <span class="c-fs28 c-fw-b c-mr-auto">{{curDateStr}}</span>
        <group class="c-textAlign-r c-fs20 datetime-theme-fc">
          <datetime title="" v-model="curDate" placeholder="请选择日期" format="YYYY-MM" :start-date="startDate" :end-date="endDate" @on-confirm="handerConfirmTime"></datetime>
        </group>
        <span class="iconfont c-fs20 theme-fc c-pl10">&#xfbcd;</span>
      </div>

      <div class="c-pt20">
        <div v-for="dateItem in list" :key="dateItem.date" class="c-pb40" :id="`${dateItem.date}_item`">
          <!-- 隐藏第一个日期，防止和顶部悬浮的日期重叠 -->
          <div v-if="dateItem.dateStr != list[0].dateStr" class="c-fs28 c-fw-b c-pv20">{{dateItem.dateStr}}</div>
          <div v-for="item in dateItem.child" :key="item.id" class="c-pt20 c-pb40 c-pl52 c-p step-box">
            <div class="c-flex-row">
              <img :src="item.headimgurl || require('@/assets/defult_head.png')" class="c-ww64 c-hh64 c-brp50" alt="" />
              <div class="c-flex-grow1 c-w0 c-ph20 c-flex-column">
                <span class="c-fs24 c-fw-b c-text-ellipsis1">{{item.nickname}}</span>
                <span class="c-pt10 theme-fc c-fs18">{{ORDER_STATUS_MAP[item.orderStatus]}}</span>
              </div>
              <div @click="tapCopyName(item.nickname)" class="c-flex-row c-flex-center c-hh24">
                <span class="c-fs20 c-fc-sblack c-pr10">复制用户昵称</span>
                <span class="iconfont c-fs24">&#xe805;</span>
              </div>
            </div>
            <div class="c-mt20 c-bg-fa c-br20 c-ph24 c-pv20 c-fs24">
              <div class="c-lh36 c-wb-ba">{{item.cnt ? '第' + item.cnt + '次':''}}访问了{{PROD_TYPE_MAP[item.pType]}}类型商品【{{item.pName}}】，浏览时长为{{!item.dur ? '0.01' : (item.dur / 60).toFixed(2)}}分钟{{item.sid ? `（分享人：${item.sNickname},ID：${item.sid}）` : ''}}</div>
              <div class="c-fs20 c-pt10 c-fc-sblack">{{item.time}}</div>
            </div>
          </div>
        </div>
      </div>
    </section>
    <loading-status-tem :dataStatus="loadingStatus" pt20="true"></loading-status-tem>
  </div>
</template>

<script>
import loadingStatusTem from '@/components/templates/common/loadingStatusTem.vue';
import CoverImg from '@/components/templates/common/coverImg.vue';
import { Datetime } from 'ckjrweb-mp-ui/src/components/index';
import { utilJs } from '@/utils/common.js';
import { LOAD_STATUS_ENUM } from '@/utils/constant.js';
import { mapState } from 'vuex';
const LIMIT = 200;
const ORDER_STATUS_MAP = {
  0: '已下单、未支付',
  1: '已成交',
  2: '未成交',
}
export default {
  name: 'shopAnalysisDetail',
  components: {
    loadingStatusTem,
    CoverImg,
    Datetime
  },
  props: [],
  computed: {
    ...mapState({
      showNavBar: (state) => state.oem_store.showNavBar,
    })
  },
  data() {
    return {
      ORDER_STATUS_MAP:ORDER_STATUS_MAP,
      PROD_TYPE_MAP: global.prodMapType,
      traceData:{},
      shopInfo: {},
      loadingStatus: ' NO_MORE_DATA', //显示加载更多LOAD_MORE 加载中 LOADING 没有更多 NO_MORE_DATA
      list: [], // 活动数据
      endDate:'', //结束日期
      endDateTime: 0, //结束的时间催
      startDate:'', //开始日期
      startDateTime: 0, //开始的时间催
      curDate: '', //当前显示的时间
      curDateStr:'',
    };
  },
  created() {
    utilJs.appShare(this);
  },
  methods: {
    tapGoDetail() {
      let toPath = `/activity/activityDetail?ActivityNo=${this._prodId}&from=activity`;
      this.$routerGo(this, "push", { path: toPath });
    },
    handerConfirmTime(val) {
      this.initList();
    },
    tapCopyName(name) {
      utilJs.copyText(name, 0).then(() => {
        this.$showCjToast({
          text: '用户昵称已复制，快去联系ta吧~',
          type: 'success'
        });
      })
    },
    checkPrice(price) {
      // 1免费 2付费且单价格（不是价格区间，不是￥1.00起这种） 3付费且多价格（有价格区间，￥1.00起这种）
      const startPrice = price.split('~')[0];
      const endPrice = price.split('~')[1];
      if (startPrice == endPrice && Number(startPrice) == 0 && Number(endPrice) == 0) {
        // 免费
        return 1;
      }
      if (Number(startPrice) != 0 && startPrice == endPrice) {
        // 付费且单价格
        return 2;
      }
      if ((Number(startPrice) != 0 || Number(endPrice) != 0) && startPrice != endPrice) {
        // 付费且多价格
        return 3;
      }
    },
    /**
     * 根据传入月份获取当前月份的最后一天日期 2024-11-30
     */
    getLastDayByMonth(monthDate) {
      let [year, month] = monthDate.toString().split('-');
      const lastDayDate = new Date(year, month, 0);
      let lastDay = lastDayDate.getDate();
      lastDay = lastDay.toString().padStart(2, '0')
      return `${year}-${month}-${lastDay}`
    },
    getList() {
      this.loadingStatus = LOAD_STATUS_ENUM.LOADING;
      //开始时间为创建时间
      const startAt = this.startDate;
      //结束时间为当前选择月份的最后一天
      const endAt = this.getLastDayByMonth(this.curDate);
      utilJs.getMethod(
        `${global.apiurl}Analyse/prod/timeline?prodId=${this._prodId}&prodType=${this._prodType}&startAt=${startAt}&endAt=${endAt}&page=${this.page}&limit=${LIMIT}&encodeUserId=${localStorage.getItem('userId')}`,
        res => {
          let resList = res.data || [];
          //重置数据结构为日期为列表的结构
          for (let item of resList) {
            let dateTime = item.t || '';
            let timeArr = dateTime.split(' ');
            item.date = timeArr[0];
            item.time = timeArr.length > 1 ? timeArr[1] : '';
            const [year, month, day] = item.date.split('-');
            item.dateStr = `${year}年${month}月${day}日`;
            let curIndex = this.list.findIndex(i => i.date == item.date);
            if (curIndex < 0) {
               let listItem = {
                date: item.date,
                dateStr: item.dateStr,
                child: [item],
              }
              this.list.push(listItem);
            } else {
               this.list[curIndex].child.push(item);
            }
          }
          this.curDateStr = this.list.length ? this.list[0].dateStr : '';
          this.startObverver();
          const { loadStatus, page } = utilJs.formatListData(this.page, LIMIT, resList, []);
          this.loadingStatus = loadStatus;
          this.page = page;
        },
        failRes => {
          this.loadingStatus = LOAD_STATUS_ENUM.DATA_ERROR;
        }
      );
    },
    getOverview() {
       utilJs.getMethod(`${global.apiurl}Analyse/prod/overview?prodId=${this._prodId}&prodType=${this._prodType}&encodeUserId=${localStorage.getItem('userId')}`, res => {
        let prodInfo = res.prodInfo || {};
        const priceInfo = utilJs.formatActivityPrice({price:prodInfo.price, payType:prodInfo.payType, showType:1});
        prodInfo.priceInfo = priceInfo;
        this.shopInfo = res.prodInfo || {};
        this.traceData = res.traceData || {};
        let createdTime = this.shopInfo.createdAt || ''
        this.startDate = createdTime.split(' ')[0];
        this.initList();
       })
    },
    /**
     * 监听每个item的滚动位置
     */
    startObverver() {
      this.intersectionObserver && this.intersectionObserver.disconnect();
      this._beforeDateStr = '';
      this.$nextTick(() => {
        for (let item of this.list) {
          this.intersectionObserver.observe(document.getElementById(`${item.date}_item`));
        }
      });
    },
    initList() {
      window.scrollTo(0, 0);
      this.page = 1;
      this.dataStatus = 'HAS_MORE_DATA';
      this.list = [];
      this.getList();
    },
    initObserver() {
      const clientWdith = document.documentElement.clientWidth || document.body.clientWidth;
      const clientHeight = document.documentElement.clientHeight || document.body.clientHeight;
      const marginBottom = this.showNavBar ? `-${(clientHeight - 68 - 40) * clientWdith / 320}px` : `-${(clientHeight - 40) * clientWdith / 320}px`
      const marginTop = this.showNavBar ? `-${68 * clientWdith / 320}px` : 0 ;
      this.intersectionObserver = new IntersectionObserver((e) => {
        if (e.length > 2) {
          return;
        }
        for (let i = 0;i < e.length;i++) {
          //当前元素进入顶部的时候，替换上方悬浮的日期，beforeDateStr是为了往回滚的时候变成上次的日期，防止滚到最上面才变
          let item = e[i];
          let isIntersecting = item.isIntersecting;
          if (isIntersecting) {
             let curDomId = item.target.id;
            const curDate = curDomId.split('_item')[0];
            const [year, month, day] = curDate.split('-');
            const curDateStr = `${year}年${month}月${day}日`;
            this._beforeDateStr = curDateStr;
            this.curDateStr = curDateStr;
          } else {
            this.curDateStr = this._beforeDateStr || this.curDateStr;
          }
        }
      }, {
        rootMargin: `${marginTop} 0px ${marginBottom} 0px`,
      })
    },
    initData() {
      this.initObserver();
      this.getOverview();
    },
    //分享
    wechatShare: function() {
      utilJs.wechatConfig('', '', '', '', function() {});
    },
    //手机端分享
    appShare: function() {
      utilJs.appShareTrue('', '', '', '');
    },
    windowScrollFunction: function() {
      utilJs.handleLoading(() => {
        if (this.loadingStatus == LOAD_STATUS_ENUM.HAS_MORE_DATA && this.list.length) {
          this.getList();
        }
      });
    },
  },
  mounted() {
    setDocumentTitle('销售线索');
    window.addEventListener('scroll', this.windowScrollFunction);
    //获取当前月份
    const nowDate = new Date();
    this.curDate = `${nowDate.getFullYear()}-${(nowDate.getMonth() + 1).toString().padStart(2, '0')}`;
    this.endDate = `${this.curDate}-${nowDate.getDate().toString().padStart(2, '0')}`;
    this._prodId = this.$route.query.prodId;
    this._prodType = this.$route.query.prodType;
    this.initData();
    this.wechatShare();
  },
  beforeDestroy() {
    this.intersectionObserver && this.intersectionObserver.disconnect();
    window.removeEventListener('scroll', this.windowScrollFunction);
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->

<style scoped>
.step-box::before{
  content: '';
  position: absolute;
  left: 0;
  top: 0.5rem;
  width:0.5rem;
  height: 0.5rem;
  border: 0.1rem solid var(--mb7color);
  border-radius: 50%;
  background-color: #fff;
}
.step-box::after{
  content: '';
  position: absolute;
  left: 0.25rem;
  top: 1rem;
  width: 1px;
  border-left:1px dashed var(--mb7color) ;
  height: 100%;
}
.step-box:last-child{
  padding-bottom: 0;
}
.step-box:last-child::after{
  display: none;
}
.btn-next {
  text-align: center;
  border-radius: 0.9rem 0px 0px 0.9rem;
  box-shadow: 0px 0px 9px 1px rgba(0, 0, 0, 0.05);
}
.btn-befor {
  text-align: center;
  border-radius: 0px 0.9rem 0.9rem 0px;
  box-shadow: 0px 0px 9px 1px rgba(0, 0, 0, 0.05);
}
</style>
